<!-- 四个关卡展示 -->
<!-- 音频播放控制 -->
<!-- 文字显示/隐藏 -->
<!-- 打乱顺序功能 --> 

<template>
  <view class="page-container">
    <!-- 顶部导航 -->
    <view class="nav-header">
      <view class="nav-content">
        <text class="nav-title">学习题目</text>
      </view>
    </view>

    <!-- 主内容区 -->
    <view class="main-content">
      <!-- 基础汉字展示 -->
      <view class="base-chars">
        <view class="base-chars-text">
          {{ baseChars.join('') }}
        </view>
      </view>

      <!-- 关卡一 -->
      <view class="level-card">
        <view class="level-header">
          <text class="level-title">第一关</text>
          <view class="level-controls">
            <view class="control-btn" @click="playAudio(levels[0], 0)">
              <image src="/static/icons/play.svg" v-if="!levels[0]?.isPlaying" class="control-icon"></image>
              <image src="/static/icons/pause.svg" v-else class="control-icon"></image>
            </view>
            <view class="control-btn" @click="toggleVisible(levels[0])">
              <image src="/static/icons/eye.svg" v-if="levels[0]?.isVisible" class="control-icon"></image>
              <image src="/static/icons/eye-off.svg" v-else class="control-icon"></image>
            </view>
          </view>
        </view>
        <view class="level-content">
          <view class="grid-3">
            <view 
              v-for="(word, wordIndex) in levels[0]?.words" 
              :key="wordIndex"
              class="word-card"
              :class="{ 'blur-sm': !levels[0]?.isVisible }"
            >
              <text class="word-text">{{ word }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 关卡二 -->
      <view class="level-card">
        <view class="level-header">
          <text class="level-title">第二关</text>
          <view class="level-controls">
            <view class="control-btn" @click="playAudio(levels[1], 1)">
              <image src="/static/icons/play.svg" v-if="!levels[1]?.isPlaying" class="control-icon"></image>
              <image src="/static/icons/pause.svg" v-else class="control-icon"></image>
            </view>
            <view class="control-btn" @click="toggleVisible(levels[1])">
              <image src="/static/icons/eye.svg" v-if="levels[1]?.isVisible" class="control-icon"></image>
              <image src="/static/icons/eye-off.svg" v-else class="control-icon"></image>
            </view>
          </view>
        </view>
        <view class="level-content">
          <view class="grid-2">
            <view 
              v-for="(word, wordIndex) in levels[1]?.words" 
              :key="wordIndex"
              class="word-card"
              :class="{ 'blur-sm': !levels[1]?.isVisible }"
            >
              <text class="word-text">{{ word }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 关卡三 -->
      <view class="level-card">
        <view class="level-header">
          <text class="level-title">第三关</text>
          <view class="level-controls">
            <view class="control-btn" @click="playAudio(levels[2], 2)">
              <image src="/static/icons/play.svg" v-if="!levels[2]?.isPlaying" class="control-icon"></image>
              <image src="/static/icons/pause.svg" v-else class="control-icon"></image>
            </view>
            <view class="control-btn" @click="toggleVisible(levels[2])">
              <image src="/static/icons/eye.svg" v-if="levels[2]?.isVisible" class="control-icon"></image>
              <image src="/static/icons/eye-off.svg" v-else class="control-icon"></image>
            </view>
          </view>
        </view>
        <view class="level-content">
          <view class="grid-2">
            <view 
              v-for="(word, wordIndex) in levels[2]?.words" 
              :key="wordIndex"
              class="word-card"
              :class="{ 'blur-sm': !levels[2]?.isVisible }"
            >
              <text class="word-text">{{ word }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 关卡四 -->
      <view class="level-card">
        <view class="level-header">
          <text class="level-title">第四关</text>
          <view class="level-controls">
            <view class="control-btn" @click="playAudio(levels[3], 3)">
              <image src="/static/icons/play.svg" v-if="!levels[3]?.isPlaying" class="control-icon"></image>
              <image src="/static/icons/pause.svg" v-else class="control-icon"></image>
            </view>
            <view class="control-btn" @click="toggleVisible(levels[3])">
              <image src="/static/icons/eye.svg" v-if="levels[3]?.isVisible" class="control-icon"></image>
              <image src="/static/icons/eye-off.svg" v-else class="control-icon"></image>
            </view>
          </view>
        </view>
        <view class="level-content">
          <view class="grid-1">
            <view 
              v-for="(word, wordIndex) in levels[3]?.words" 
              :key="wordIndex"
              class="word-card"
              :class="{ 'blur-sm': !levels[3]?.isVisible }"
            >
              <text class="word-text">{{ word }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部功能按钮 -->
    <view class="bottom-buttons">
      <view class="button-group">
        <button class="shuffle-btn" @click="shuffleWords">
          打乱顺序
        </button>
        <button class="generate-btn" @click="regenerate">
          重新生成
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useUserStore } from '@/store/modules/user'

// 基础数据
const baseChars = ref([])
const levels = ref([])
const exerciseId = ref('')

// 初始化数据
const initData = async () => {
  try {
    // 从本地存储获取练习数据
    const exerciseData = uni.getStorageSync('currentExerciseData')
    console.log('初始化数据, 练习数据:', JSON.stringify(exerciseData, null, 2))
    
    if (!exerciseData) {
      throw new Error('练习数据不存在')
    }
    
    exerciseId.value = exerciseData.id
    
    // 处理基础汉字
    if (Array.isArray(exerciseData.baseChars)) {
      baseChars.value = exerciseData.baseChars
    } else if (typeof exerciseData.baseChars === 'string') {
      baseChars.value = exerciseData.baseChars.split('')
    } else {
      baseChars.value = []
      console.warn('baseChars 格式异常:', exerciseData.baseChars)
    }
    
    console.log('处理后的基础汉字:', baseChars.value)
    
    // 处理关卡数据
    const content = exerciseData.content || {}
    console.log('关卡内容:', content)
    
    levels.value = [
      {
        words: Array.isArray(content.level_1) ? content.level_1 : [],
        audioUrl: exerciseData.audioUrl1 || '',
        isVisible: true,
        isPlaying: false
      },
      {
        words: Array.isArray(content.level_2) ? content.level_2 : [],
        audioUrl: exerciseData.audioUrl2 || '',
        isVisible: true,
        isPlaying: false
      },
      {
        words: Array.isArray(content.level_3) ? content.level_3 : [],
        audioUrl: exerciseData.audioUrl3 || '',
        isVisible: true,
        isPlaying: false
      },
      {
        words: Array.isArray(content.level_4) ? content.level_4 : [],
        audioUrl: exerciseData.audioUrl4 || '',
        isVisible: true,
        isPlaying: false
      }
    ]
    
    console.log('处理后的关卡数据:', JSON.stringify(levels.value, null, 2))
    
    // 检查是否有数据
    const hasContent = levels.value.some(level => level.words.length > 0)
    if (!hasContent) {
      throw new Error('题目内容为空')
    }
  } catch (error) {
    console.error('初始化数据失败:', error)
    uni.showToast({
      title: error.message || '加载失败',
      icon: 'none',
      duration: 2000
    })
    
    // 跳转回生成页面
    setTimeout(() => {
      uni.switchTab({
        url: '/pages/generate/index'
      })
    }, 2000)
  }
}

// 音频播放控制
const audioContext = uni.createInnerAudioContext()
const playAudio = (level, index) => {
  // 如果正在播放,则停止
  if (level.isPlaying) {
    audioContext.stop()
    level.isPlaying = false
    return
  }
  
  // 停止其他正在播放的音频
  levels.value.forEach(item => {
    item.isPlaying = false
  })
  
  // 播放当前音频
  audioContext.src = level.audioUrl
  audioContext.play()
  level.isPlaying = true
  
  // 播放结束时重置状态
  audioContext.onEnded(() => {
    level.isPlaying = false
  })
}

// 显示/隐藏控制
const toggleVisible = (level) => {
  level.isVisible = !level.isVisible
}

// 打乱顺序
const shuffleWords = async () => {
  try {
    // 调用打乱接口
    const res = await uni.request({
      url: `https://paintasong.cn/api/exercise/shuffle/${exerciseId.value}`,
      method: 'POST',
      header: {
        'Authorization': 'Bearer ' + uni.getStorageSync('token')
      }
    })
    
    if (res.data.code === 0) {
      const data = res.data.data
      // 更新关卡数据
      levels.value = levels.value.map((level, index) => {
        return {
          ...level,
          words: data.content[`level_${index + 1}`]
        }
      })
    } else {
      throw new Error(res.data.message || '操作失败')
    }
  } catch (error) {
    // API调用失败时在本地打乱
    levels.value = levels.value.map(level => {
      return {
        ...level,
        words: level.words.sort(() => Math.random() - 0.5)
      }
    })
  }
}

// 重新生成
const regenerate = () => {
  uni.switchTab({
    url: '/pages/generate/index'
  })
}

// 页面加载时获取数据
onMounted(() => {
  // 优先从页面参数获取ID
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const id = currentPage.options?.id
  
  console.log('学习页面加载, 参数id:', id)
  
  // 从本地存储获取练习数据
  const exerciseData = uni.getStorageSync('currentExerciseData')
  console.log('本地存储的练习数据:', exerciseData)
  
  if (exerciseData) {
    // 直接初始化数据
    initData()
  } else if (id) {
    // 如果有ID但没有数据，从服务器获取
    fetchExerciseData(id)
  } else {
    // 如果没有数据也没有ID，尝试从历史记录获取最新练习
    fetchLatestExercise()
  }
})

// 从服务器获取练习数据
const fetchExerciseData = async (id) => {
  try {
    const res = await uni.request({
      url: `https://paintasong.cn/api/exercise/detail/${id}`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + uni.getStorageSync('token')
      }
    })
    
    console.log('获取练习详情响应:', res.data)
    
    if (res.data.code === 0) {
      // 保存数据到本地存储
      uni.setStorageSync('currentExerciseData', res.data.data)
      // 初始化数据
      initData()
    } else {
      throw new Error(res.data.message || '获取练习详情失败')
    }
  } catch (error) {
    console.error('获取练习详情失败:', error)
    uni.showToast({
      title: error.message || '加载失败',
      icon: 'none',
      duration: 2000
    })
    
    // 跳转回生成页面
    setTimeout(() => {
      uni.switchTab({
        url: '/pages/generate/index'
      })
    }, 2000)
  }
}

// 获取最新练习
const fetchLatestExercise = async () => {
  try {
    const res = await uni.request({
      url: 'https://paintasong.cn/api/exercise/latest',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + uni.getStorageSync('token')
      }
    })
    
    console.log('获取最新练习响应:', res.data)
    
    if (res.data.code === 0 && res.data.data) {
      // 保存数据到本地存储
      uni.setStorageSync('currentExerciseData', res.data.data)
      // 初始化数据
      initData()
    } else {
      // 如果没有历史练习，提示用户生成新题目
      console.log('没有找到历史练习')
      uni.showToast({
        title: '请先生成题目',
        icon: 'none',
        duration: 2000
      })
      
      // 延迟跳转，让用户看到提示
      setTimeout(() => {
        uni.switchTab({
          url: '/pages/generate/index'
        })
      }, 2000)
    }
  } catch (error) {
    console.error('获取最新练习失败:', error)
    uni.showToast({
      title: error.message || '加载失败',
      icon: 'none',
      duration: 2000
    })
    
    // 跳转回生成页面
    setTimeout(() => {
      uni.switchTab({
        url: '/pages/generate/index'
      })
    }, 2000)
  }
}

// 页面卸载时停止音频
onUnmounted(() => {
  audioContext.destroy()
})

// 分享配置
defineExpose({
  onShareAppMessage() {
    return {
      title: '快来和我一起学习汉字吧',
      path: `/pages/study/index?id=${exerciseId.value}`
    }
  }
})
</script>

<style lang="scss">
.page-container {
  width: 375px;
  margin: 0 auto;
  min-height: 100vh;
  background: #fff;
  position: relative;
}

.nav-header {
  position: fixed;
  top: 0;
  width: 375px;
  z-index: 50;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  padding-top: env(safe-area-inset-top);
}

.nav-content {
  height: 48px;
  padding: 0 16px;
  display: flex;
  align-items: center;
}

.nav-title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.main-content {
  padding-top: calc(48px + env(safe-area-inset-top));
  padding-left: 20px;
  padding-right: 20px;
  padding-bottom: calc(64px + env(safe-area-inset-bottom));
}

.base-chars {
  margin-top: 24px;
  margin-bottom: 32px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 12px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.base-chars-text {
  font-size: 28px;
  font-weight: 600;
  line-height: 1.4;
  color: #1a1a1a;
  display: flex;
  justify-content: center;
  gap: 48px;
}

.level-card {
  margin-bottom: 24px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.level-header {
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.level-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.level-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.control-btn {
  width: 36px;
  height: 36px;
  background: #f0f7ff;
  transition: all 0.2s;

  &:active {
    background: #e1f0ff;
  }
}

.control-icon {
  width: 24px;
  height: 24px;
}

.level-content {
  padding: 16px 20px;
}

.grid-1 {
  display: grid;
  grid-template-columns: 1fr;
  gap: 8px;
}

.grid-2 {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
}

.grid-3 {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 8px;
}

.word-card {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 12px;
  min-height: 44px;
  border: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: center;

  &.blur-sm {
    filter: blur(5px);
  }
}

.word-text {
  font-size: 16px;
  font-weight: 500;
  color: #1a1a1a;
}

.bottom-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 375px;
  background: #fff;
  border-top: 1px solid #f0f0f0;
  padding: 12px 20px;
  padding-bottom: calc(env(safe-area-inset-bottom));
  box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.05);
  height: 64px;
}

.button-group {
  display: flex;
  gap: 12px;
  margin: 0 4px;
  height: 44px;
}

.shuffle-btn, .generate-btn {
  flex: 1;
  height: 44px;
  border-radius: 22px;
  font-size: 16px;
  font-weight: 600;
  transition: all 0.2s;
}

.shuffle-btn {
  background: #f5f7fa;
  color: #444;
  border: 1px solid #eee;

  &:active {
    background: #eee;
  }
}

.generate-btn {
  background: linear-gradient(135deg, #2196F3, #1976D2);
  color: #fff;

  &:active {
    transform: scale(0.98);
  }
}
</style> 